package com.stephen.mycc.launcher.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.stephen.mycc.launcher.R;
import com.stephen.mycc.launcher.ripple.StephenRippleButton;

import java.io.Serializable;

public class BaseActivity extends FragmentActivity implements View.OnClickListener{
    public static final String ParamBase = "ParamBase",ParamExtra1 = "ParamExtra1",ParamExtra2 = "ParamExtra2",
            ParamExtra3 = "ParamExtra3",ParamExtra4 = "ParamExtra4",ParamExtra5 = "ParamExtra5",ResultBase = "ResultBase";
    protected BaseActivity activity;
    private Bundle paramBundle = null;
    private Intent resultIntent = null;
    public StephenCommonNoDataView stephenCommonNoDataView;
    public StephenCommonTopTitleView stephenCommonTopTitleView;
    public InputMethodManager imm;
    public MainHandler mainHandler;
    public boolean isCheckPlatform = false,isPad = false;//当前是phone/pad
    private long firstKeyTime = 0;//第一次按键时间
    public int width = 0,height = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PointF pointF = StephenToolUtils.getScreenWidthHeightPixels(this);
        width = (int)pointF.x;//宽度
        height = (int)pointF.y;//高度
        if(isCheckPlatform)changeRunningMode(null);//判断运行平台
    }

    //切换运行模式
    protected void changeRunningMode(Boolean isTvMode){
        if(null == isTvMode){
            if(StephenToolUtils.checkCurRunningIsPad(this)){//pad
                isPad = true;
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }else{//phone
                isPad = false;
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        }else{
            if(isTvMode){
                isPad = true;
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }else{//pad/phone
                if(StephenToolUtils.checkCurRunningIsPad(this)){
                    isPad = true;
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }else{//phone
                    isPad = false;
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            }
        }
        //StephenToolUtils.showShortHintInfo(this,(isPad ? "Pad" : "Phone")+"===>"+getResources().getConfiguration().smallestScreenWidthDp);
    }

    protected void mainInitMethod(BaseActivity activity) {
        mainInitFunction(activity);
    }

    protected void mainInitMethod(BaseActivity activity,int mainLayoutId) {
        setContentView(mainLayoutId);
        mainInitFunction(activity);
    }

    protected void mainInitMethod(BaseActivity activity,View mainLayoutV) {
        setContentView(mainLayoutV);
        mainInitFunction(activity);
    }

    //初始化
    protected void mainInitFunction(BaseActivity activity){
        this.activity = activity;
        this.mainHandler = new MainHandler(activity.getMainLooper());
        imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        initializeActivityData();//初始化数据,比如getIntent
        initializeFunction();//初始化界面
        getActivityContentData();//获取设置界面数据
    }

    public void initializeActivityData(){}//会自动调用

    //其实是initializeFunction主要完成初始化界面相关的事情
    protected void initializeFunction() {}//会自动调用

    public boolean getActivityContentData(Object... objects) {//会自动调用
        return true;
    }

    public void reInitializationRefreshData(Object... objects){//有需要手动调用
        initializeActivityData();
        getActivityContentData(objects);
    }

    public void getActivityFilterContent() {}//有需要手动调用

    ////////////////////////////////////Intent Param Start//////////////////////////////////////////

    //获取跳转传多个参数并判空处理
    public Intent getCurIntent(){
        return (null == getIntent()) ? (new Intent()) : getIntent();
    }

    //重置
    public void restCurBundle(){
        paramBundle = null;
    }

    //跳转Activity传多个参数用
    public Bundle getCurBundle(){
        if(null == paramBundle)paramBundle = new Bundle();
        return paramBundle;
    }

    //获取传递给Activity序列化对象
    public Serializable getSerializableParamObject(){
        return getCurIntent().getSerializableExtra(ParamBase);
    }

    //构造传递给Activity序列化对象
    public Bundle buildSerializableParamBundle(Serializable objVal){
        if(null != objVal)getCurBundle().putSerializable(ParamBase,objVal);
        return paramBundle;
    }

    //构造传递给Activity序列化对象,嵌套两层
    public Bundle buildSerializableParamBundleTwice(Serializable objVal){
        if(null != objVal)getCurBundle().putBundle(ParamBase,buildFragmentParamBase(objVal));
        return paramBundle;
    }

    //构造准备传递给下一页包含的Fragment参数,跳页时
    public Bundle buildFragmentParamBundle(Serializable objVal){
        Bundle bundle = new Bundle();
        bundle.putBundle(BaseFragment.ParamBase,buildFragmentParamBase(objVal));
        return bundle;
    }

    //构造准备传递给本页包含的Fragment参数,跳页时
    public Bundle buildFragmentParamBase(Serializable objVal){
        Bundle paramBundle = new Bundle();
        if(null != objVal)paramBundle.putSerializable(BaseFragment.ParamBase,objVal);
        return paramBundle;
    }

    //获取准备传递给包含的Fragment参数
    public Bundle getFragmentParamBundle(){
        Bundle paramBundle = getCurIntent().getBundleExtra(BaseFragment.ParamBase);
        if(null != paramBundle)return paramBundle;
        return new Bundle();
    }

    //返回给Activity传多个参数用
    public Intent getResultIntent(){
        if(null == resultIntent)resultIntent = new Intent();
        return resultIntent;
    }

    //构造返回给Activity序列化对象
    public Intent buildResultSerializableObject(Serializable objVal){
        return getResultIntent().putExtra(ResultBase,objVal);
    }
    ////////////////////////////////////Intent Param End//////////////////////////////////////////

    //切换显示系统输入法
    public void toggleSystemInputMethod() {
        if (null != imm) imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    //显示系统输入法
    public void showSystemInputMethod(View view) {
        if (null != imm && null != view) {
            imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        }//end of if
    }

    //隐藏系统输入法
    public void hideSystemInputMethod(View view) {
        if (null != imm && null != view && null != view.getWindowToken()) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }//end of if
    }

    //得到view实例
    public <T extends View> T findUiViewToInstantiation(int viewId) {
        return (T) findViewById(viewId);
    }

    public <T extends View> T findUiViewToInstantiation(View mainV, int viewId) {
        return (T) mainV.findViewById(viewId);
    }

    //设置监听事件,得到id
    public void setUiViewClickListener(int... viewIds) {
        for (int viewId : viewIds) setUiViewClickListener(findUiViewToInstantiation(viewId));
    }

    //设置监听事件,得到view
    public void setUiViewClickListener(View... views) {
        if (null != views && views.length > 0)for (View view : views) if (null != view) view.setOnClickListener(this);
    }

    //设置波纹是否可绘制在视图之外
    public void setUiButtonRippleClipChild(StephenRippleButton... btns) {
        if (null != btns && btns.length > 0)for (StephenRippleButton btn : btns) if (null != btn) btn.setRippleCanClip(false);
    }

    //设置波纹按钮开始是否在中心
    public void setUiButtonRippleIsCenterCircle(boolean isCenterCircle,StephenRippleButton... btns) {
        if (null != btns && btns.length > 0)for (StephenRippleButton btn : btns) if (null != btn) btn.setIsCenterCircle(isCenterCircle);
    }

    //设置组件屏蔽父控件处理touch事件
    public void setDisallowParentInterceptTouchEvent(View... views) {
        if (null != views && views.length > 0) {
            for (View view : views){
                if (null != view){
                    view.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            if(null == v || null == v.getParent())return false;
                            v.getParent().requestDisallowInterceptTouchEvent(true);
                            return true;
                        }
                    });
                }//end of if
            }//end of for
        }//end of if
    }

    @Override
    public void onClick(View view) {
        hideSystemInputMethod(view);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {//点击空白区域,隐藏输入法
            View view = getCurrentFocus();
            if (null != view && StephenToolUtils.isShouldHideKeyboard(view, ev))
                hideSystemInputMethod(view);
        }//end of if
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            StephenToolUtils.closeLoadingDialog();
            StephenToolUtils.closeAlertInfoDialog();
            if (null != mainHandler) mainHandler.removeCallbacksAndMessages(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                onSystemMenuClick();
                break;
            case KeyEvent.KEYCODE_BACK:
                if(backCheckOperation()){
                    if(needExitActivity()){
                        long secondTime = System.currentTimeMillis();
                        if(secondTime - firstKeyTime > 2000){ //如果两次按键时间间隔大于2秒
                            StephenToolUtils.showShortHintInfo(BaseActivity.this, "再快速按一次退出");
                            firstKeyTime = secondTime;//更新firstTime
                            return true;
                        }else{//两次按键小于2秒时
                            minimizationProgram();
                        }
                    }else{
                        backPrevActivityPage();
                    }
                }//end of if
                break;
        }//end of switch
        return true;
        //return super.onKeyUp(keyCode, event);
    }

    //系统菜单点击
    protected void onSystemMenuClick(){}

    //直接退出的activity
    public boolean needExitActivity() {
        return false;
    }

    //返回上一步
    public void backPrevActivityPage(){
        backPrevActivityPage(-1);
    }
    public void backPrevActivityPage(int exitAnim){
        if(null != activity)activity.finish();
        overridePendingTransition(0, (-1 == exitAnim) ? R.anim.slide_translate_left : exitAnim);
    }

    //返回时检查操作
    public boolean backCheckOperation(){
        return true;//default
    }

    //菜单左边按键响应
    public void backBtnClickResponse(){
        if(backCheckOperation())backPrevActivityPage();//default
    }
    public void backBtnClickResponse(int exitAnim){
        if(backCheckOperation())backPrevActivityPage(exitAnim);//self
    }

    //关闭程序之前的操作
    public void beforeFinishProgram() {}

    //最小化程序
    public void minimizationProgram() {
        beforeFinishProgram();
        moveTaskToBack(true);
    }

    //完全退出
    public void completelyExitProgram(){
        minimizationProgram();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    //handler
    public class MainHandler extends Handler {
        public MainHandler(Looper looper) {}

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case VickyConfig.msg_showInfo:
                    StephenToolUtils.showLongHintInfo(BaseActivity.this, String.valueOf(msg.obj));
                    break;
                case VickyConfig.msg_showLoading:
                    String hintStr = "拼命加载数据中...";
                    if (null != msg.obj && msg.obj instanceof String)hintStr = msg.obj.toString();
                    StephenToolUtils.showLoadingDialog(BaseActivity.this, hintStr);
                    break;
                case VickyConfig.msg_closeLoading:
                    StephenToolUtils.closeLoadingDialog();
                    break;
                case VickyConfig.msg_showInput://UI线程里面显示输入法可能无效
                    if (null != imm)imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    break;
                default:
                    disposeMainHandlerCallMethod(msg);
                    break;
            }//end of switch
        }
    }

    //显示loading对话框
    public void showLoadingDialog(String hintStr) {
        if(null != mainHandler){
            Message msg = Message.obtain();
            msg.what = VickyConfig.msg_showLoading;
            msg.obj = hintStr;
            mainHandler.sendMessage(msg);
        }//end of if
    }

    //关闭loading对话框
    public void closeLoadingDialog() {
        if(null != mainHandler)mainHandler.sendEmptyMessage(VickyConfig.msg_closeLoading);
    }

    protected void disposeMainHandlerCallMethod(Message msg) {//处理handler消息
        //System.out.println("subclass override method operation!switch_ msg.what");
    }
}
